package com.xunshibao.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;

/**
 * 为controller的方法参数创建自定义的参数类型解析器 当mvc框架在给方法注入参数时，就会调用该方法，如果满足条件，返回相应的类型
 * 该方法是从session中解析user对象，如果没有找到相应的类型返回UNRESOLVED
 * 该类必须和AnnotationMethodHandlerAdapter配合使用customArgumentResolver
 * 
 * @author ThinkPad
 * 
 */
public class CustomerArgumentResolver implements WebArgumentResolver {

    @Override
    public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception {
        if (methodParameter.getParameterType().equals(SessionUser.class)) {
            return webRequest.getAttribute(SessionUser.KEY, RequestAttributes.SCOPE_SESSION);
        }
        if (methodParameter.getParameterType().equals(IpAddress.class)) {
            String ip = webRequest.getHeader("x-forwarded-for");
            if (ip == null) {
                ip = webRequest.getNativeRequest(HttpServletRequest.class).getRemoteAddr();
            }
            return ip;
        }
        return UNRESOLVED;
    }

}
